
const treeDataFormat = function (arr, idKey, parentKey, subsName = 'subs') {
  var treeUtil = {
    treeDataFormat(arr, idKey, parentKey) {
      var results = [];
      //根节点(父节点)必须在数组前面,
      arr.sort(function (a, b) {
        //以level和seq字段来排序
        if (a.level == b.level) {
          if (a.seq > b.seq) {
            return 1
          } else {
            return -1
          }
        } else {
          if (a.level > b.level) {
            return 1;
          } else {
            return -1;
          }
        }
      });
      var obj;
      let sorceData = arr;
      let a = 1;
      while (sorceData.length) {
        obj = sorceData[0];
        sorceData.splice(0, 1); //取玩之后删除第0个
        // delete obj[parentKey];
        obj.index = a + '';
        obj.title = obj.name;
        var node = this.getAllChildren(sorceData, obj, idKey, parentKey); //不含有自己的list和自己(item)传过去,获取所有自己的子节点,然后掉方法
        a++;
        results.push(node);
      }
      return results;
    },
    getAllChildren(list, item, idKey, parentKey) {
      var subs = this.getNextLevelChildren(list, item, idKey, parentKey);
      for (var i = 0, j = subs[subsName].length; i < j; i++) {
        subs[subsName][i] = this.getAllChildren(list, subs[subsName][i], idKey, parentKey);
      }
      return subs;
    },
    getNextLevelChildren(list, item, idKey, parentKey) {
      var subs = [];
      let a = 1;
      for (var i = 0; i < list.length; i++) {
        //查找子节点
        var obj = list[i];
        if (obj[parentKey] === item[idKey]) {
          // obj.parentid = obj.parentId;
          // delete obj[parentKey];
          obj.index = item.index + '-' + a;
          obj.title = obj.name;
          a++;
          subs.push(obj);
          list.splice(i, 1);
          i--;
        }
      }
      item[subsName] = subs;
      return item;
    }
  }
  return treeUtil.treeDataFormat(arr, idKey, parentKey);
}
export { treeDataFormat }